<template>
  <div>
    <n-card title="场景信息" :header-style="{padding: '10px 10px 0px 10px'}" :content-style="{padding: '5px 5px 5px 5px'}">
      <template #header-extra>
        <n-space justify="end" style="margin-bottom: 5px">
          <n-button type="warning" size="small" @click="sceneExtract" :loading="nameExtractLoading">
            推理场景
          </n-button>
          <n-button type="primary" size="small" @click="resetFormData();addSceneShow = true;">新增场景
          </n-button>
        </n-space>
      </template>
      <n-scrollbar
        :style="{ height: `${(clientHeight - (layoutHeaderHeight  + tabsHeight) - 350)/2}px` }"
        trigger="none">
      <n-table striped>
        <thead>
        <tr>
          <th style="width: 120px">操作</th>
          <th>场景名称</th>
          <th>场景描述</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="scene in sceneList">
          <td>
            <n-button style="width: 50px;" type="warning" size="small" @click="deleteScene(scene.id)">删除
            </n-button>
            <n-button style="width: 50px;margin-left: 5px" type="primary" size="small"
                      @click="editScene(scene)">编辑
            </n-button>
          </td>
          <td>{{ scene.sceneName }}</td>
          <td>{{ scene.sceneDescription }}</td>
        </tr>
        </tbody>
      </n-table>
      </n-scrollbar>
    </n-card>
    <n-modal
        v-model:show="addSceneShow"
        class="custom-card"
        style="width: 600px"
        preset="card"
        title="编辑场景"
        size="huge"
        :bordered="false"
    >
      <n-form
          ref="formRef"
          label-placement="left"
          :label-width="100"
          :style="{
            maxWidth: '640px'
          }"
          :rules="rules"
          :model="sceneForm"
      >
        <n-form-item label="场景名称" path="sceneName">
          <n-input v-model:value="sceneForm.sceneName"/>
        </n-form-item>
        <n-form-item label="场景描述" path="sceneDescription">
          <n-input v-model:value="sceneForm.sceneDescription" type="textarea" style="height: 100px;">
          </n-input>
          <n-button type="primary" style="height: 100px; margin-left: 5px;" @click="promptTemplateShow = true">
            提示词器
          </n-button>
        </n-form-item>
      </n-form>
      <n-space justify="end">
        <n-button type="primary" @click="addScene" :loading="addSceneLoading">确定</n-button>
      </n-space>
    </n-modal>
  </div>
  <commonPromptChat :commonPromptSetting="commonPromptSetting" :closeAction="closeAction" v-model:show="commonPromptChatShow"></commonPromptChat>

</template>
<script setup lang="ts">
import {h, onMounted, reactive, ref} from "vue";
import {storySceneController} from "@/api/controller/story/storySceneController";
import {storyCharacterController} from "@/api/controller/story/storyCharacterController";
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import CommonPromptChat from "@/components/gpt/common/commonPromptChat.vue";
import {JsonUtils} from "@/utils/jsonUtils";
import {NH5, NTag} from "naive-ui";

const nameExtractLoading = ref(false)
const addSceneShow = ref(false)
const promptTemplateShow = ref(false)
const sceneList = ref({})
const addSceneLoading = ref(false)
const formRef = ref(null)
const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const commonPromptChatShow = ref(false)

onMounted(() => {
  getSceneList()
})



const props = defineProps({
  storyId: {
    type: String,
    required: true
  },
  storyContent:{
    type: String,
    required: true
  }
})

const commonPromptSetting :Chat.CommonPromptSetting = {
  bizType: "custom_extract_scene",
  bizData: [],
  resultRequire: "",
  saveResultFunction: (results:any) => {
    const isJSONArray = JsonUtils.isJsonArray(results[0].result)
    if (isJSONArray){
      const scenceArray = JSON.parse(results[0].result)
      window.$dialog.info({
        title: "提醒",
        content: ()=>{
          let node = []
          node.push(h(NTag, {type: 'info',style: 'margin-left:2px'}, {default: () => '提取了 (' + scenceArray.length +') 个场景'}))
          scenceArray.forEach((item: any) => {
            node.push(
                h(NTag, {type: 'info',style: 'margin-left:2px'},
                    {default: () => '场景名称 (' + item.name +')'}))
          })
          node.push(h(NH5,{showIcon:false},{default: () => '是否保存场景信息 ' }))
          return node;
        },
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
          const sceneArr = ref([])
          scenceArray.forEach((item: any) => {
            const scene = {
              sceneName: item.name,
              sceneDescription: item.description
            }
            sceneArr.value.push(scene)
          })
          storySceneController.batchAddScene(sceneArr.value,props.storyId).then(res => {
            if (res.code === 200) {
              commonPromptChatShow.value = false
              window.$message.success(res.msg)
              getSceneList()
            } else {
              window.$message.error(res.msg)
            }
          })
        }
      })
    }else {
      window.$message.error("返回的格式不对,可能为大模型推理错误,请重新推理，或者修改格式...")
    }
  },
  warningText: "推理文本过多会导致以下问题: \r 1) 大语言模型生成的时间过长，有可能会导致超时... \r 2) 超出模型的上下文限制，导致请求出错... \r 3) 建议文本字数控制在1000字以内...",
}
const sceneForm = ref(reactive({
  sceneName: '',
  sceneDescription: '',
  chapterId: props.storyId,
  id: ''
}))

const resetFormData = () => {
  sceneForm.value = {
    sceneName: '',
    sceneDescription: '',
    chapterId: props.storyId,
    id: ''
  }
}

const rules = {
  sceneName: [
    {required: true, message: '请输入场景名称', trigger: 'submit'}
  ],
  sceneDescription: [
    {required: true, message: '请输入场景描述', trigger: 'submit'}
  ]
}

const getSceneList = () => {
  storySceneController.getSceneList(props.storyId).then(res => {
    if (res.code === 200) {
      sceneList.value = res.data
      console.log(sceneList.value)
    }
  })
}


const sceneExtract = () => {
  const bizData = ref([])
  const promptData = {
    'id': props.storyId,
    'index': 0 ,
    'content': props.storyContent,
    'result': ''
  }
  bizData.value.push(promptData)
  commonPromptSetting.bizData =  bizData.value
  commonPromptChatShow.value = true

  // nameExtractLoading.value = true
  // const param = {
  //   chapterId: props.storyId
  // }
  // storySceneController.sceneExtract(param).then(res => {
  //   if (res.code === 200) {
  //     getSceneList()
  //   } else {
  //     window.$message.error(res.data)
  //   }
  // }).finally(() => {
  //   nameExtractLoading.value = false
  // })
}


const editScene = (scene: any) => {
  sceneForm.value.sceneName = scene.sceneName
  sceneForm.value.sceneDescription = scene.sceneDescription
  sceneForm.value.id = scene.id
  addSceneShow.value = true
}

const deleteScene = (sceneId: string) => {
  window.$dialog.error({
    title: "温馨提醒",
    content: "删除操作不可逆，是否继续？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      storySceneController.deleteScene(sceneId).then(res => {
        if (res.code === 200) {
          window.$message.success(res.msg)
          getSceneList()
        }
      })
    }
  })
}

const addScene = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      addSceneLoading.value = true
      storySceneController.addScene(sceneForm.value).then(res => {
        addSceneLoading.value = false
        addSceneShow.value = false
        if (res.code === 200) {
          window.$message.success("操作成功!")
          getSceneList()
        }
      })
    }
  })
}

const closeAction = ()=>{
  commonPromptChatShow.value = false
}

</script>
